package com.example.mapperapi.file;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("file")
public class FileController {
    @Autowired
    private FileUtil fileUtil;

    @GetMapping("{fileIndex}")
    public void downFile(@PathVariable String fileIndex, HttpServletResponse response) {
        byte[] bytes = fileUtil.getBytes(fileIndex);
        if (bytes == null) {
            return;
        }
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileIndex + ".jpg");
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            outputStream.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        fileUtil.remove(fileIndex);
    }
}
